#include "FileWriter.h"
#include "BitStream.h"

void FileWriter::openFile(const string &filename)
{
    _file.open(filename, fstream::out | fstream::trunc | fstream::binary);
}

bool FileWriter::writeFileHeader(int width, int height, QuantizationMatrix &qm)
{
    uint32_t widthToWrite = (uint32_t)width;
    uint32_t heigthToWrite = (uint32_t)height;

    _file.write((char*)(&widthToWrite), 4);
    _file.write((char*)(&heigthToWrite), 4);
    for(int i = 0; i < qm.columnLength()*qm.columnLength(); ++i)
    {
        uint8_t qmVal = (uint8_t)qm[i];
        _file.write((char*)&qmVal, 1);
    }

    return true;

}

void FileWriter::writeFrameHeader(uint8_t type, uint32_t bitsWritten)
{
    uint8_t buffer[4];
    util::BitStreamWriter bsw(buffer, 4);
    bsw.put_bit(type);
    bsw.put(31, bitsWritten);
    if(!_file.fail())
        util::write(_file, bsw);
}

bool FileWriter::writeData(util::BitStreamWriter* bsw)
{
    bool status=false;

    if(bsw->get_position()%8 != 0)
        bsw->flush();

    if((status = !_file.fail()))
    {
        util::write(_file, *bsw);
    }

    return status;
}

bool FileWriter::writeData(uint8_t *data, int length)
{
    _file.write((char*)data, length);

    return true;
}

void FileWriter::closeFile()
{
    _file.close();
}
